package io.xxx.omni.osc.sdk

import com.alibaba.fastjson.JSONObject
import io.xxx.omni.osc.domain.Store
import org.apache.commons.codec.digest.DigestUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import org.springframework.web.client.RestTemplate
import org.springframework.web.util.UriComponentsBuilder
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

@Component
class BbsClient {

    @Autowired
    private lateinit var restTemplate: RestTemplate

    private val httpUrl = "http://platform.meitun.com"

    private val formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss")

    fun execute(store: Store, path: String, request: Map<String, Any>): JSONObject {
        val authorization = store.authorization
        val timestamp = LocalDateTime.now().format(formatter)
        val apiVersion = "v6.0"
        val sign = DigestUtils.md5Hex(authorization["appKey"] + authorization["accessToken"] + timestamp + apiVersion)
            .uppercase()
        val url = UriComponentsBuilder
            .fromHttpUrl(httpUrl)
            .path(path)
            .queryParam("appkey", authorization["appKey"])
            .queryParam("version", apiVersion)
            .queryParam("timestamp", timestamp)
            .queryParam("sign", sign)
            .toUriString()
        return restTemplate.postForEntity(url, request, JSONObject::class.java).body!!
    }
}